package controller;


import javax.servlet.http.HttpSession;
import model.User;
import org.apache.log4j.Logger;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import dao.IUserDAO;

@Controller
@SessionAttributes("userInfo")
public class LoginController {

	@Autowired
	@Qualifier("userServices")
	private IUserDAO userDao;
	
	static  Logger log = Logger.getLogger(CRUDController.class.getName());
	
	public LoginController() {
		log.info("init Login Controller");
	}
	
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public ModelAndView doLogin(@RequestParam("username") String username,
						  @RequestParam("password") String password) {
		ModelAndView myModelView = new ModelAndView();
		User user = (User) userDao.getOneUser(username);
//		if(user != null && password.equals(user.getPassword())){
			if(user != null && BCrypt.checkpw(password, user.getPassword())){
			myModelView.addObject("userInfo", user);
			if(user.getType() != 0 && user.getType() != 1){
				myModelView.setViewName("waitting");
				log.info("login with guest account successfully");
				return myModelView;
			}
			myModelView.setViewName("default");
			log.info("login successfully");
			return myModelView;
		}
		log.info("login failed");
			return new ModelAndView("welcome","error","error");
	}
	
	
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String doLogout(ModelMap map, HttpSession session) {
			session.setAttribute("userInfo", null);
			map.remove("userInfo");
			log.info("logout successfully");
		return "welcome";
	}
	}
